//
//  PhotoListViewController.m
//  Malena
//
//  Created by Dawn on 12-11-3.
//  Copyright (c) 2012年 Dawn. All rights reserved.
//

#import "PhotoListViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "InfoViewController.h"
#import "UIView+ModalAnimation.h"
#import "ShareKit.h"

#define TOOLBUTTONTAG 1000
#define THUMBNAILVIEWHEIGHT 94
#define TOOLBARWIDTH 200
#define TOOLBARHEIGHT 45



@interface PhotoListViewController ()
- (void) addSplashToView;
- (void) addPageToView;
- (void) addToolBarToView;
- (void) addTipsView;
- (void) addThumbnailsView;
- (void) slideTips;
@end

@implementation PhotoListViewController
@synthesize category = _category;
@synthesize imageData = _imageData;

- (void) dealloc{
    self.category = nil;
    self.imageData = nil;
    [shareSheet release];
    [super dealloc];
}

- (id) init{
    if (self = [super init]) {
        // 初始化默认数据
        
        // 提取文件中的分类
        NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
        id category = [userDefaults objectForKey:@"category"];
        categoryIndex = 0;
        if (category) {
            categoryIndex = [category intValue];
        }
       
        // 载入图片分类
        self.category = [NSArray arrayWithContentsOfFile:RESOURCEFILE(@"Category", @"plist")];
        
        if (categoryIndex >= self.category.count) {
            categoryIndex = 0;
        }
        
        // 载入上一次选中分类下的图片
        NSString *dataFileName = [[self.category objectAtIndex:categoryIndex] objectForKey:@"DataFile"];
        self.imageData = [NSArray arrayWithContentsOfFile:RESOURCEFILE(dataFileName, @"plist")];
        
        // 计算第一个分类下的图片数量
        imageCount = [self.imageData count];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveUserDefaults) name:APPLICATIONWILLTERMINATE object:nil];
    }
    return  self;
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)viewDidLoad{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor blackColor];
    
    // 大图翻页
    [self addPageToView];
    
    // 工具条
    [self addToolBarToView];
    
    // 照片描述
    [self addTipsView];
    
    // 缩略图
    [self addThumbnailsView];
    
    // 闪屏
    [self addSplashToView];
    
    // 启动闪屏动画
    [self splash];
}

#pragma mark -
#pragma mark Views
// 添加闪屏
- (void) addSplashToView{
    // 判断当前Controller的方向是否与设备方向一致，以此来进行界面布局
    // 闪屏
    if (self.interfaceOrientation == UIDeviceOrientationPortrait || self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown){
        splashView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    }else{
        splashView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH)];
    }
    splashView.backgroundColor = [UIColor whiteColor];
    splashView.alpha = 1;
    splashView.userInteractionEnabled = NO;
    
    [self.view addSubview:splashView];
    [splashView release];
}

// 添加大图翻页
- (void) addPageToView{
    NSMutableArray *dataArray = [[NSMutableArray alloc] initWithCapacity:self.imageData.count];
    for (NSDictionary *dict in self.imageData) {
        [dataArray addObject:RESOURCEFILE([dict objectForKey:@"name"], @"jpg")];
    }
    
    if (self.interfaceOrientation == UIDeviceOrientationPortrait || self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown){
        photoPageView = [[PhotoPageView alloc] initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH,SCREEN_HEIGHT) files:dataArray];
    }else{
        photoPageView = [[PhotoPageView alloc] initWithFrame: CGRectMake(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH) files:dataArray];
    }
    [dataArray release];
    photoPageView.delegate = self;
    
    [self.view addSubview:photoPageView];
    [photoPageView release];
    
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    id photoPage = [userDefaults objectForKey:@"photoPage"];
    photoPageIndex = 0;
    if (photoPage) {
        photoPageIndex = [photoPage intValue];
    }
    if (photoPageIndex >= imageCount) {
        photoPageIndex = 0;
    }
    if(photoPageIndex >0){
        [photoPageView quickPageToIndex:photoPageIndex];
    }

}

// 添加工具条
- (void) addToolBarToView{
    NSArray *toolIconArray = [NSArray arrayWithObjects:@"galleries.png",@"thumbnails.png",@"play.png",@"info.png",@"email.png", nil];
    
    if (self.interfaceOrientation == UIDeviceOrientationPortrait || self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown){
        toolBarView = [[CircleToolBarView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - TOOLBARWIDTH, 0, TOOLBARWIDTH, TOOLBARWIDTH) iconArray:toolIconArray position:CircleToolBarRightTop];
    }else{
        toolBarView = [[CircleToolBarView alloc] initWithFrame:CGRectMake(SCREEN_HEIGHT - TOOLBARWIDTH, 0, TOOLBARWIDTH, TOOLBARWIDTH) iconArray:toolIconArray position:CircleToolBarRightTop];
    }
    
    [self.view addSubview:toolBarView];
    [toolBarView release];
    
    toolBarView.delegate = self;
}

// 照片描述信息
- (void) addTipsView{
    if (self.interfaceOrientation == UIDeviceOrientationPortrait || self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown){
        tipsView = [[TipsView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 20, SCREEN_WIDTH, 100)];
        tipsView.screenSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
    }else{
        tipsView = [[TipsView alloc] initWithFrame:CGRectMake(0, SCREEN_WIDTH - 20, SCREEN_HEIGHT, 100)];
        tipsView.screenSize = CGSizeMake(SCREEN_HEIGHT, SCREEN_WIDTH);
    }
    NSString *tips = [[self.imageData objectAtIndex:photoPageIndex] objectForKey:@"description"];
    
    tipsView.tips = tips;
    tipsView.title = [[self.category objectAtIndex:categoryIndex] objectForKey:@"Name"];
    
    [self.view addSubview:tipsView];
    [tipsView release];
}

// 缩略图
- (void) addThumbnailsView{
    photosView = nil;
    if (self.interfaceOrientation == UIDeviceOrientationPortrait || self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown){
        photosView = [[PhotosView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, THUMBNAILVIEWHEIGHT)];
        photosView.screenSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
    }else{
        photosView = [[PhotosView alloc] initWithFrame:CGRectMake(0, SCREEN_WIDTH,SCREEN_HEIGHT, THUMBNAILVIEWHEIGHT)];
        photosView.screenSize = CGSizeMake(SCREEN_HEIGHT, SCREEN_WIDTH);
    }
    [self.view addSubview:photosView];
    [photosView release];
    
    photosView.delegate = self;
    
    // 重新计算文件路径
    NSMutableArray *dataArray = [[NSMutableArray alloc] initWithCapacity:self.imageData.count];
    for (NSDictionary *dict in self.imageData) {
        NSString *fileName = [NSString stringWithFormat:@"%@_thumb",[dict objectForKey:@"name"]];
        [dataArray addObject:RESOURCEFILE(fileName, @"jpg")];
    }
    [photosView reloadDataWith:dataArray];
    [dataArray release];
    photosView.category = [[self.category objectAtIndex:categoryIndex] objectForKey:@"Name"];
}

#pragma mark -
#pragma mark Private methods
- (void) slideTips{
    [UIView beginAnimations:@"ToolViewAction" context:nil];
    [UIView setAnimationDuration:0.3];
    if (toolBarView.frame.origin.y >= 0) {
        toolBarView.frame = CGRectOffset(toolBarView.frame, 0,- TOOLBARHEIGHT);
        if (tipsView.frame.origin.y < tipsView.screenSize.height) {
            tipsView.down = YES;
            tipsView.frame = CGRectMake(0, tipsView.screenSize.height - tipsView.frame.size.height, tipsView.frame.size.width, tipsView.frame.size.width);
            
        }
    }else{
        toolBarView.frame = CGRectOffset(toolBarView.frame, 0, TOOLBARHEIGHT);
        if (tipsView.frame.origin.y >= tipsView.screenSize.height) {
            tipsView.down = NO;
            tipsView.frame = CGRectMake(0, tipsView.screenSize.height, tipsView.frame.size.width, tipsView.frame.size.width);
        }
    }
    if (photosView.frame.origin.y < photosView.screenSize.height) {
        photosView.down = YES;
        photosView.frame = CGRectMake(0, photosView.screenSize.height, photosView.frame.size.width, photosView.frame.size.height);
    }
    
    [UIView commitAnimations];
}

// 闪屏动画
- (void) splash{
    splashView.alpha = 1.0f;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:2.0f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    splashView.alpha = 0.0f;
    [UIView commitAnimations];
}



#pragma mark -
#pragma mark PhotosViewDelegate
- (void) photosView:(PhotosView *)photosView didSelectedAtIndex:(NSInteger)index{
    [photoPageView pageToIndex:index animated:NO];
}

#pragma mark -
#pragma mark PhotoPageViewDelegate
- (void) photoPageView:(PhotoPageView *)pageView didPagedToIndex:(NSInteger)index{
    [photoPageView stopAutoScroll];
    [toolBarView setIsPlaying:NO];
    
    NSString *tips = [[self.imageData objectAtIndex:index] objectForKey:@"description"];
    
    tipsView.tips = tips;
    
    [UIView beginAnimations:@"ThumbnailAction" context:nil];
    [UIView setAnimationDuration:0.3];
    if (photosView.frame.origin.y < photosView.screenSize.height) {
        [self switchTipsViewWithPhotosView];
    }
    [UIView commitAnimations];
    
    [photosView performSelector:@selector(scrollToIndex:) withObject:[NSNumber numberWithInt:index] afterDelay:0.3];
    
}

- (void) photoPageView:(PhotoPageView *)pageView didSelectedAtIndex:(NSInteger)index{
    [self slideTips];
    [photoPageView stopAutoScroll];
    [toolBarView setIsPlaying:NO];
    [toolBarView closeItems];
    
}

- (void) switchPhotosViewWithTipsView{
    photosView.down = NO;
    photosView.frame = CGRectMake(0, photosView.screenSize.height - photosView.frame.size.height, photosView.frame.size.width, photosView.frame.size.height);
    NSLog(@"%f,%f,%f,%f",photosView.frame.origin.x,photosView.frame.origin.y,photosView.frame.size.width,photosView.frame.size.height);
    
    if (tipsView.frame.origin.y < tipsView.screenSize.height) {
        tipsView.down = YES;
        tipsView.frame = CGRectMake(0, tipsView.screenSize.height, tipsView.frame.size.width, tipsView.frame.size.height);
    }
}

- (void) switchTipsViewWithPhotosView{
    photosView.down = YES;
    photosView.frame = CGRectMake(0, photosView.screenSize.height, photosView.frame.size.width, photosView.frame.size.height);
    
    if (tipsView.frame.origin.y >= tipsView.screenSize.height) {
        tipsView.down = NO;
        tipsView.frame = CGRectMake(0, tipsView.screenSize.height - tipsView.frame.size.height, tipsView.frame.size.width, tipsView.frame.size.height);
    }
}

#pragma mark -
#pragma mark CircleToolBarViewDelegate
- (void) didSelectedAtIndex:(NSInteger)index{
    switch (index) {
        case 0:{        // 选择分类
            CategoryViewController *categoryVC = [[CategoryViewController alloc] init];
            categoryVC.categoryData = self.category;
            categoryVC.delegate = self;
            if (IOSVersion_5) {
                [self presentViewController:categoryVC animated:YES completion:nil];
            }else{
                [self presentModalViewController:categoryVC animated:YES];
            }
            [categoryVC release];
            break;
        }
        case 1:{        // 缩略图
            [UIView beginAnimations:@"ToolViewAction" context:nil];
            [UIView setAnimationDuration:0.4];
            
            if (photosView.frame.origin.y >= photosView.screenSize.height) {
                [self switchPhotosViewWithTipsView];
            }else{
                [self switchTipsViewWithPhotosView];
            }

            [UIView commitAnimations];
            break;
        }
        case 2:{        // 自动播放
            if (toolBarView.isPlaying) {
                [self slideTips];
                [photoPageView startAutoScroll];
            }else{
                [photoPageView stopAutoScroll];
            }
            break;
        }
        case 3:{        // 简介
            InfoViewController *infoViewController = [[InfoViewController alloc] init];
            if (IOSVersion_5) {
                [self presentViewController:infoViewController animated:YES completion:nil];
            }else{
                [self presentModalViewController:infoViewController animated:YES];
            }
            [infoViewController release];
            break;
        }
        case 4:{        // 分享
            if (IOSVersion_6) {
                ShareKit *shareKit = [ShareKit share];
                shareKit.contentViewController = self;
                [shareKit shareBySystemKitWithContent:tipsView.tips image:photoPageView.currentImage];
            }else{
                shareSheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"Share", nil)
                                                         delegate:self
                                                cancelButtonTitle:NSLocalizedString(@"Cancel",nil)
                                           destructiveButtonTitle:nil
                                                otherButtonTitles:NSLocalizedString(@"Mail", nil), nil];
                shareSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
                [self.view addSubview:shareSheet];
                [shareSheet showInView:self.view];
            }
            break;
        }
        default:
            break;
    }
}

#pragma mark -
#pragma mark UIActionSheetDelegate
- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        ShareKit *shareKit = [ShareKit share];
        shareKit.contentViewController = self;
        [shareKit shareByMailWithTitle:tipsView.title content:tipsView.tips image:photoPageView.currentImage];
    }
}


#pragma mark - 
#pragma mark CategoryViewControllerDelegate
- (void) didSelectedCateforyAtIndex:(NSInteger)index{
    
    splashView.alpha = 0.0f;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:2.0f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationDelegate:self];
    splashView.alpha = 1.0f;
    [UIView commitAnimations];
    
    [self performSelector:@selector(exchangeCategory:) withObject:[NSNumber numberWithInteger:index] afterDelay:2.0f];
}

- (void)exchangeCategory:(id)obj{
    NSInteger index = [obj intValue];
    
    splashView.alpha = 1.0f;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1.2f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationDelegate:self];
    splashView.alpha = 0.0f;
    [UIView commitAnimations];
    
    //切换分类重新加载数据
    NSString *dataFileName = [[self.category objectAtIndex:index] objectForKey:@"DataFile"];
    self.imageData = [NSArray arrayWithContentsOfFile:RESOURCEFILE(dataFileName, @"plist")];
    
    // 重新计算图片数量
    imageCount = [self.imageData count];
    
    // 重置大图容器
    NSMutableArray *dataArray = [[NSMutableArray alloc] initWithCapacity:self.imageData.count];
    for (NSDictionary *dict in self.imageData) {
        [dataArray addObject:RESOURCEFILE([dict objectForKey:@"name"], @"jpg")];
    }
    
    
    [photoPageView reloadDataWith:dataArray];
    [dataArray release];

    // 重置缩略图
    NSMutableArray *thumbDataArray = [[NSMutableArray alloc] initWithCapacity:self.imageData.count];
    for (NSDictionary *dict in self.imageData) {
        NSString *fileName = [NSString stringWithFormat:@"%@_thumb",[dict objectForKey:@"name"]];
        [thumbDataArray addObject:RESOURCEFILE(fileName, @"jpg")];
    }
    [photosView reloadDataWith:thumbDataArray];
    photosView.category = [[self.category objectAtIndex:index] objectForKey:@"Name"];
    [thumbDataArray release];
    
    // 重新设置tips
    NSString *tips = [[self.imageData objectAtIndex:0] objectForKey:@"description"];
    tipsView.tips = tips;
    tipsView.title = [[self.category objectAtIndex:index] objectForKey:@"Name"];

    
    // 记录分类到文件
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:[NSNumber numberWithInt:index] forKey:@"category"];
    [userDefaults synchronize];
}



#pragma mark -
#pragma mark UIViewControllerRotation
// 支持旋转
- (BOOL)shouldAutorotate{
    return YES;
}

// 支持所有的方向
- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskAll;
}

-(BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
	return YES;
}

- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
    // 恢复旋转时隐藏的控件
    photosView.hidden = NO;
    tipsView.hidden = NO;
    NSLog(@"did rotate");
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    NSLog(@"will animate rotate");
    
    // 排除全屏旋转时的干扰
    if (photosView.down) {
        photosView.hidden = YES;
    }
    if (tipsView.down) {
        tipsView.hidden = YES;
    }
    

}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    
    NSLog(@"will rotate");
    
   
    switch (toInterfaceOrientation) {
        case UIInterfaceOrientationLandscapeLeft:{
                       
        }
        case UIInterfaceOrientationLandscapeRight:{
            // 主图片区域
            photoPageView.frame = CGRectMake(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH);
            
            // 缩略图区域
            photosView.screenSize = CGSizeMake(SCREEN_HEIGHT, SCREEN_WIDTH);
            if (photosView.down) {
                photosView.frame = CGRectMake(0, SCREEN_WIDTH, SCREEN_HEIGHT, THUMBNAILVIEWHEIGHT);
            }else{
                photosView.frame = CGRectMake(0, SCREEN_WIDTH - THUMBNAILVIEWHEIGHT, SCREEN_HEIGHT, THUMBNAILVIEWHEIGHT);
            }
            
            // 闪屏
            splashView.frame = CGRectMake(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH);
            
            // 工具栏
            toolBarView.frame = CGRectMake(SCREEN_HEIGHT - TOOLBARWIDTH, toolBarView.frame.origin.y, TOOLBARWIDTH, TOOLBARWIDTH);
            
            // 描述
            tipsView.screenSize = CGSizeMake(SCREEN_HEIGHT, SCREEN_WIDTH);
            if (tipsView.down) {
                tipsView.frame = CGRectMake(0, SCREEN_WIDTH, SCREEN_HEIGHT, 100);
            }else{
                tipsView.frame = CGRectMake(0, SCREEN_WIDTH - tipsView.frame.size.height, SCREEN_HEIGHT, 100);
            }
            break;
        }
        case UIInterfaceOrientationPortrait:{
            
            
        }
        case UIInterfaceOrientationPortraitUpsideDown:{
            // 主图片区域
            photoPageView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
            
            // 缩略图区域
            photosView.screenSize = CGSizeMake(SCREEN_WIDTH,SCREEN_HEIGHT);
            if (photosView.down) {
                photosView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, THUMBNAILVIEWHEIGHT);
            }else{
                photosView.frame = CGRectMake(0, SCREEN_HEIGHT - THUMBNAILVIEWHEIGHT, SCREEN_WIDTH, THUMBNAILVIEWHEIGHT);
            }
            
            // 闪屏
            splashView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
            
            // 工具栏
            toolBarView.frame = CGRectMake(SCREEN_WIDTH - TOOLBARWIDTH, toolBarView.frame.origin.y, TOOLBARWIDTH, TOOLBARWIDTH);
            
            // 描述
            tipsView.screenSize = CGSizeMake(SCREEN_WIDTH,SCREEN_HEIGHT);
            if (tipsView.down) {
                tipsView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 100);
            }else{
                tipsView.frame = CGRectMake(0, SCREEN_HEIGHT - 100, SCREEN_WIDTH, 100);
            }
            
            break;
        }
        default:
            break;
    }
    
    photosView.hidden = NO;
    tipsView.hidden = NO;
}

#pragma mark -
#pragma mark Notification
- (void) saveUserDefaults{
    // 记录分类到文件
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:[NSNumber numberWithInt:photoPageView.page] forKey:@"photoPage"];
    [userDefaults synchronize];
}

@end
